<?php
/**
 * 满减模型
 * @version 2015092916
 * @author Justin <justin@jipu.com>
 */

namespace Shop\Model;

class ManjianModel extends AdminModel{
  
  /**
   * 自动验证规则
   * @var array
   * @author Max.Yu <max@jipu.com>
   */
  protected $_validate = array(
    array('name', 'require', '活动名称不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    array('expire_time', 'require', '请选择结束时间', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    array('man', 'require', '满多少不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    array('jian', 'require', '减多少不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
  );

  /**
   * 自动完成规则
   * @var array
   * @author Max.Yu <max@jipu.com>
   */
  protected $_auto = array(
    array('create_time', NOW_TIME, self::MODEL_INSERT),
    array('update_time', NOW_TIME, self::MODEL_BOTH),
    array('start_time', '_getStartTime', self::MODEL_BOTH, 'callback'),
    array('expire_time', 'strtotime', self::MODEL_BOTH, 'function'),
  );
  
  /**
   * 获取开始时间
   * @author BUDDHA <[email address]>
   * @return   [type]                   [description]
   */
  protected function _getStartTime(){
    return I('post.start_time') ? strtotime(I('post.start_time')) : time();
  }


  public function update(){
      $data = $this->create();
      if($data['start_time'] >= $data['expire_time']){
          $this->error = "开始时间不能小于结束时间!";
          return false;
      }
      if ($data['jian'] >= $data['man'] ) {
         $this->error = "减少金额不能大于满足金额!";
          return false;
      }
      if($data['id']){
          $where['id'] = array('neq',$data['id']);
      }
      $where['store_id'] = $this->store_id;
      $where['status'] = 1;
      $where['_string'] = "(start_time <={$data['start_time']} and expire_time >= {$data['start_time']}) or (start_time <={$data['expire_time']} and expire_time >= {$data['expire_time']})";
      $result = $this->where($where)->find();
      if($result){
          $this->error = "该时间段内您已添加过满减活动，请更改活动时间!";
          return false;
      }
      $res = $data['id'] ? $this->save($data) : $this->add($data);
      //记录行为
      action_log('update_'.CONTROLLER_NAME, CONTROLLER_NAME, $data['id'] ? $data['id'] : $res, UID);
      return $res;
  }
  
}
